package org.ibase4j.web.sys;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ibase4j.model.SceneType;
import org.ibase4j.model.sys.BarcodeScene;
import org.ibase4j.model.sys.SysUserRole;
import org.ibase4j.service.sys.BarcodeProcess;
import org.ibase4j.service.sys.BarcodeSceneService;
import org.ibase4j.service.sys.SysAuthorizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import top.ibase4j.core.base.BaseController;
import top.ibase4j.core.base.provider.Parameter;
import top.ibase4j.core.exception.BusinessException;
import top.ibase4j.core.support.context.ApplicationContextHolder;
import top.ibase4j.core.util.DataUtil;

/**
 * <p>
 * 二维码场景表  前端控制器
 * </p>
 *
 * @author zoyee
 * @since 2018-08-06
 */
@Controller
@RequestMapping("/scene")
@Api(value = "二维码场景表接口", description = "二维码场景表接口")
public class BarcodeSceneController extends BaseController<BarcodeScene, BarcodeSceneService> {
	@Autowired
	private SysAuthorizeService sysAuthorizeService;

	@RequiresPermissions("barcodeScene.read")
	@PutMapping(value = "/read/list")
	@ApiOperation(value = "查询二维码场景表")
	public Object query(ModelMap modelMap, @RequestBody Map<String, Object> param) {
		return super.query(modelMap, param);
	}

	@PutMapping(value = "/getBarcode")
	@ApiOperation(value = "获取二维码场景")
	public Object fetchBarcode(ModelMap modelMap, @RequestBody BarcodeScene param) {
		if(param.getSceneType() == null || DataUtil.isEmpty(param.getKeyword())) {
			throw new BusinessException("缺少参数");
		}
		param.setKeyword(param.getKeyword().trim());
		boolean match = false;
		for (SceneType sceneType : SceneType.values()) {
			if(sceneType.getCode() == param.getSceneType().intValue()) {
				match = true;
				BarcodeScene result = this.service.fetchBarcode(sceneType, param.getKeyword());
				return setSuccessModelMap(modelMap, result);
			}
		}
		if(!match) {
			throw new BusinessException("缺少匹配的场景");
		}
		return setSuccessModelMap(modelMap, null);
	}
	
	@PostMapping(value = "/perform")
	@ApiOperation(value = "条码二维码扫码执行场景")
	public Object perform(ModelMap modelMap, HttpServletRequest request, @RequestBody BarcodeScene param) {
		if(param.getSceneType() == null || DataUtil.isEmpty(param.getSceneId())) {
			throw new BusinessException("缺少参数");
		}
		BarcodeScene scene = this.service.queryBySceneId(param.getSceneId(), param.getSceneType());
		if(scene != null) {
			String operation = scene.getOperation();
			if(DataUtil.isNotEmpty(operation)) {
				//校验扫码次数
				if(scene.getScanLimit() != null && scene.getScanCount().longValue() >= scene.getScanLimit().longValue()) {
					throw new BusinessException("扫码次数已打上限限制");
				}
				//校验扫码权限
				if(scene.getScanUserRole() != null) {
					if(getCurrUser() == null) {
						throw new BusinessException("扫码权限限制，没有权限");
					}else {
						List<SysUserRole> retList = sysAuthorizeService.getRolesByUserId(getCurrUser(request));
						boolean match = false;
						for (SysUserRole userRole : retList) {
							if(userRole.getRoleId().longValue() == scene.getScanUserRole()) {
								match = true;
								break;
							}
						}
						if(!match) {
							throw new BusinessException("扫码权限限制，没有权限");
						}
					}
				}
				//校验二维码时效
				if(scene.getValidDateTime() != null) {
					Date now = new Date();
					if(now.getTime() > scene.getValidDateTime().getTime()) {
						throw new BusinessException("二维码已失效");
					}
				}
				
				BarcodeProcess process = (BarcodeProcess)ApplicationContextHolder.getBean(operation);
				Object result = process.execute(scene.getData());
				
				//更新扫码次数
				scene.setScanCount(scene.getScanCount() + 1);
				super.update(modelMap, scene);
				return setSuccessModelMap(modelMap, result);
			}
			return setSuccessModelMap(modelMap, scene);
		} else {
			throw new BusinessException("没有匹配的场景");
		}
		
	}
	
	@PostMapping(value = "/write/save")
	@RequiresPermissions("barcodeScene.update")
	@ApiOperation(value = "修改二维码场景表")
	public Object update(ModelMap modelMap, @RequestBody BarcodeScene param) {
		return super.update(modelMap, param);
	}

	@DeleteMapping(value = "/delete")
	@RequiresPermissions("barcodeScene.delete")
	@ApiOperation(value = "(逻辑)删除二维码场景表")
	public Object del(ModelMap modelMap, HttpServletRequest request, @RequestBody BarcodeScene param) {
		return super.del(modelMap, request, param);
	}
}